using UnityEngine;
using System.Collections;

public class Turret_Gunner : MonoBehaviour {
	
	public float fireInterval;
	public int damage;
	public float rotationSpeed = 2;
	public GameObject[] firePoints = new GameObject[4];
	public Bullet bullet;
	public GameObject target;
	public float timer;
	
	
	void Start () 
	{
		
	}
	
	void Update () 
	{
		if (target != null)
		{
			RotateTo(target.transform.position);
			timer += 1 * Time.deltaTime;
			
			if (timer > fireInterval)
			{
				Fire(firePoints.Length);
			}
		}
		
	}
	
	void RotateTo (Vector3 targetPosition)
	{
		Quaternion finalRotation;
		Vector3 relativePos;
		relativePos = targetPosition - transform.position;
		finalRotation = Quaternion.LookRotation(relativePos);	
		transform.rotation = Quaternion.Slerp(transform.rotation, finalRotation, rotationSpeed);
	}
	
	void Fire (int r)
	{
		for (int i = 0; i < r; i++)
		{
			Bullet Temp;
			Temp = Instantiate (bullet, firePoints[i].transform.position, transform.rotation) as Bullet;
			Temp.setup(target, damage);
		}
		timer = 0;
	}
	
	void OnTriggerStay (Collider other)
	{
		if (other.CompareTag("enemy1"))
		{
			if (target == null)
			{
				target = other.gameObject;
			}
			else
			{
				if (Vector3.Distance (gameObject.transform.position, other.gameObject.transform.position) <=
					Vector3.Distance (gameObject.transform.position, target.transform.position))
				{
					target = other.gameObject;
				}
			}
		}
	}
	
	void OnTriggerExit (Collider other)
	{
		target = null;	
	}
}
